<template>
	<div>
		<el-card>
			<el-form :model="state.pageParam.param" label-width="80"  ref="queryFormRef" @keyup.enter.native="loadList">
				<el-row :gutter="10">
					<el-col :xs="3" :sm="4" :md="4" :lg="6" :xl="6">
						<el-form-item prop="approveNo" label="审批编号">
							<el-input v-model="state.pageParam.param.approveNo" class="task-head-search-input"  placeholder="审批编号" clearable>
							</el-input>
						</el-form-item>
					</el-col>
					<el-col :xs="3" :sm="4" :md="4" :lg="6" :xl="6">
						<el-form-item label="流程名称" prop="processDefName">
							<el-input v-model="state.pageParam.param.processDefName" placeholder="流程名称" clearable></el-input>
						</el-form-item>
					</el-col>
					<el-col :xs="3" :sm="4" :md="4" :lg="6" :xl="6">
						<el-form-item label="流程摘要" prop="briefReport">
							<el-input v-model="state.pageParam.param.briefReport" placeholder="流程摘要" clearable></el-input>
						</el-form-item>
					</el-col>
					<el-col :xs="3" :sm="4" :md="4" :lg="6" :xl="6">
						<el-form-item label="发起时间" prop="queryStartTime">
							<el-date-picker v-model="state.pageParam.param.queryStartTime" type="daterange" placeholder="发起时间" :shortcuts="datePickershortcuts" value-format="YYYY-MM-DD"></el-date-picker>
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
			<div class="btnSearchStyle">
				<el-button type="primary" class="ml7" @click="loadList">
					<el-icon>
						<ele-Search />
					</el-icon>
					查询
				</el-button>
				<el-button type="primary" class="ml10" @click="reSetForm(queryFormRef)">
					<el-icon>
						<ele-Refresh />
					</el-icon>
					重置
				</el-button>
			</div>
		</el-card>
		<el-card>
			<el-table :data="state.dataList" stripe style="width: 100%" v-loading="state.listLoading">
				<el-table-column header-align="center" align="center" prop="approveNo" label="流程编码"/>
				<el-table-column header-align="center" align="center" prop="processDefName" label="流程名称"/>
				<el-table-column header-align="center" align="center" prop="briefReport" label="流程摘要"/>
				<el-table-column header-align="center" align="center" prop="startUserName" label="发起人"/>
				<el-table-column header-align="center" align="center" prop="startTime" label="开始时间"/>
				<el-table-column header-align="center" align="center" prop="endTime" label="结束时间"/>
				<el-table-column header-align="center" align="center" prop="assigneeName" label="当前处理人"/>
				<el-table-column header-align="center" align="center" prop="processState" label="流程状态" column-key="process_ins_state" :formatter="formatStatus"/>
				<el-table-column header-align="center" align="center" prop="deleteReason" label="终止原因"/>
				<el-table-column header-align="center" align="center" fixed="right" width="250" label="操作">
					<template #default="scope">
						<el-button type="primary" link @click="trace(scope.row)" >跟踪</el-button>
						<el-button type="primary" link v-if="scope.row.processState == 'ACTIVE'" @click="stopProcess(scope.row)">终止</el-button>
						<el-button type="primary" link v-if="scope.row.processState == 'ACTIVE'" @click="transferProcess(scope.row)">转办</el-button>
						<el-button type="primary" link @click="showProcessTaskHis(scope.row)" >审批记录</el-button>
					</template>
				</el-table-column>
			</el-table>
			<el-pagination
				@size-change="onHandleSizeChange"
				@current-change="onHandleCurrentChange"
				:pager-count="5"
				:page-sizes="[10, 50, 200]"
				v-model:current-page="state.pageParam.page"
				background
				v-model:page-size="state.pageParam.pageSize"
				layout="total, sizes, prev, pager, next, jumper"
				:total="state.total" small>
			</el-pagination>
		</el-card>
		<el-dialog title="流程跟踪" v-model="state.processStateview" width="95%" style="height:600px" destroy-on-close>
			<processStateViewer :processId="state.selectTask.processId"></processStateViewer>
		</el-dialog>
		<el-dialog title="审批记录" v-model="state.taskHisVisible" width="75%">
			<el-table :data="state.hisProcessRecordData" stripe v-loading="state.detailLoading">
				<el-table-column label="节点" prop="taskName"></el-table-column>
				<el-table-column label="审批人" prop="assigneeName"></el-table-column>
				<el-table-column label="处理状态" prop="taskState" column-key="ProcessRecordState" :formatter="formatStatus"></el-table-column>
				<el-table-column label="处理结果" prop="description" column-key="processResult" :formatter="formatStatus"></el-table-column>
				<el-table-column label="处理意见" prop="approveAdvice"></el-table-column>
				<el-table-column label="开始时间" prop="startTime"></el-table-column>
				<el-table-column label="结束时间" prop="endTime"></el-table-column>
			</el-table>
		</el-dialog>
		<el-dialog title="流程转办" v-model="state.userCheckView" width="95%" style="height:600px" destroy-on-close>
			<el-form :model="state.userPageParam.param" label-width="80"  ref="userQueryFormRef" @keyup.enter.native="loadUserList">
				<el-row :gutter="10">
					<el-col :xs="3" :sm="4" :md="4" :lg="6" :xl="6" >
						<el-form-item label="用户名" prop="username">
							<el-input v-model="state.userPageParam.param.username" placeholder="用户名" maxlength="50"></el-input>
						</el-form-item>
					</el-col>
					<el-col :xs="3" :sm="4" :md="4" :lg="6" :xl="6" >
						<el-form-item label="员工编号" prop="staffId">
							<el-input v-model="state.userPageParam.param.staffId" placeholder="员工编号" maxlength="50"></el-input>
						</el-form-item>
					</el-col>
					<el-col :xs="3" :sm="4" :md="4" :lg="6" :xl="6" >
						<el-form-item label="姓名" prop="staffName">
							<el-input v-model="state.userPageParam.param.staffName" placeholder="姓名" maxlength="50"></el-input>
						</el-form-item>
					</el-col>
					<el-col :xs="3" :sm="4" :md="4" :lg="6" :xl="6" >
						<el-form-item label="组织机构" prop="orgId">
							<el-input v-model="state.userPageParam.param.orgName" placeholder="组织机构" clearable></el-input>
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
			<div class="btnSearchStyle">
				<el-button type="primary" class="ml7" @click="loadList">
					<el-icon>
						<ele-Search />
					</el-icon>
					查询
				</el-button>
				<el-button type="primary" class="ml10" @click="reSetUserForm(queryFormRef)">
					<el-icon>
						<ele-Refresh />
					</el-icon>
					重置
				</el-button>
			</div>
			<el-table :data="state.userDataList" stripe style="width: 100%" v-loading="state.userListLoading">
				<el-table-column prop="username" header-align="center" align="center" label="用户名" />
				<el-table-column prop="staffId" header-align="center" align="center" label="员工编号" />
				<el-table-column prop="staffName" header-align="center" align="center" label="姓名" />
				<el-table-column prop="status" header-align="center" align="center" label="用户状态" column-key="1002" :formatter="formatStatus" />
				<el-table-column prop="orgName" header-align="center" align="center" label="组织机构" />
				<el-table-column fixed="right" header-align="center" align="center" width="250" label="操作">
					<template #default="scope">
						<el-button type="primary" link @click="doTransferProcess(scope.row)">选择</el-button>
					</template>
				</el-table-column>
			</el-table>
			<el-pagination @size-change="onUserHandleSizeChange" @current-change="onUserHandleCurrentChange" :pager-count="5"
					:page-sizes="[10, 50, 200]" v-model:current-page="state.userPageParam.page" background
					v-model:page-size="state.userPageParam.pageSize" layout="total, sizes, prev, pager, next, jumper"
					:total="state.userTotal" small>
			</el-pagination>
		</el-dialog>
	</div>
</template>
<script setup lang="ts" name="processManage">
import { ElLoading, ElMessage, ElMessageBox, FormInstance } from 'element-plus';
import { createVNode, defineAsyncComponent, onMounted, reactive, ref } from 'vue';
import { TaskVo, workflowApi } from '/@/api/sys/workflow-api'
import { getDataDictionaryList } from '/@/utils/cacheDic';
import { datePickershortcuts } from '/@/utils/constans'
import { systemApi } from '/@/api/sys/system-api';

const processStateViewer = defineAsyncComponent(() => import('./processStateViewer.vue'))
const queryFormRef = ref<FormInstance>()
const userQueryFormRef = ref<FormInstance>()
const state = reactive({
	listLoading: false,
	total: 0,
	dataList: [],
	dataListSelections: [],
	dataDictionaryList: {} as any,
	pageParam: {
		page: 1,
		pageSize: 10,
		param: {
			approveNo: '',
			processDefName: '',
			briefReport: '',
			queryStartTime: [],
		}
	},
	userCheckView: false,
	userListLoading: false,
	userPageParam: {
		page: 1,
		pageSize: 10,
		param: {
			username: '',
			staffName: '',
			tenantId: '',
			staffId: '',
			orgId: '',
			orgName: '',
		}
	},
	userDataList: [],
	userTotal: 0,
	selectTask: {
		taskId: '',
		processId: '',
		businessKey: '',
	},
	processStateview: false,
	taskHisVisible: false,
	detailLoading: false,
	hisProcessRecordData: [] as TaskVo[],
	transferProcessTaskId: '',
})

const loadList = () => {
	state.listLoading = true
	workflowApi.queryProcessPage(state.pageParam).then(data => {
		if (data && data.code === 0) {
			state.dataList = data.data.records
			state.total = data.data.totalRow
		} else {
			state.dataList = []
			state.total = 0
		}
	}).catch(() => {
	}).finally(() => {
		state.listLoading = false
	})
}
// 页面加载时
onMounted(() => {
	// 数据字典
	getDataDictionaryList(state.dataDictionaryList, ['process_ins_state', 'ProcessRecordState', 'processResult', '1002'])
	// 列表查询
	loadList()
})

//重置
const reSetForm = (formEl: FormInstance | undefined) => {
	if (!formEl) return
	formEl.resetFields()
	state.pageParam.page = 1
	loadList()
}
// 分页改变
const onHandleSizeChange = (val: number) => {
	state.pageParam.pageSize = val;
	loadList()
}
// 分页改变
const onHandleCurrentChange = (val: number) => {
	state.pageParam.page = val;
	loadList()
}
const formatStatus = (row: any, column: any, cellValue: string | number) => {
	if(Object.keys(state.dataDictionaryList).length>0){
		if (cellValue) {
			return state.dataDictionaryList[column.columnKey].get(cellValue);
		}
	}
}
//流程图
const trace = (row: any) => {
	state.selectTask.taskId = row.taskId
	state.selectTask.processId = row.processInstanceId
	state.selectTask.businessKey = row.businessKey
	state.processStateview = true
}
//终止流程
const stopProcess = (row: any) => {
	const h = createVNode
	ElMessageBox.prompt(h('p', null, [h('i', {style: 'color: red'}, '*'), h('span', null, '终止原因')]), '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		inputPattern: /^.+$/,
		inputErrorMessage: '请输入终止原因'
	}).then(({ value }) => {
		 //提交数据
		 const loading = ElLoading.service({
			lock: true,
			text: '处理中',
			background: 'rgba(0, 0, 0, 0.7)',
		})
		workflowApi.deleteProcess(row.processInstanceId, value).then((data) => {
			if(data.code === 0){
				ElMessage.success('流程终止成功')
			}else{
				ElMessage.error(data.message)
			}
			loadList()
		}).catch(() => {
			ElMessage.error('流程终止失败')
		}).finally(() => {
			loading.close()
		})
	})
}
const showProcessTaskHis = (row: any) => {
	state.taskHisVisible = true
	state.detailLoading = true
	workflowApi.getHisTaskByProcessId(row.processInstanceId).then((data) => {
		if (data.code === 0) {
			state.hisProcessRecordData = data.data
		}
	}).finally(() => {
		state.detailLoading = false
	})
}
const loadUserList = () => {
	state.userListLoading = true
	systemApi.querySysUserListPage(state.userPageParam).then(data => {
		if (data && data.code === 0) {
			state.userDataList = data.data.records
			state.userTotal = data.data.totalRow
		} else {
			state.userDataList = []
			state.userTotal = 0
		}
	}).catch(() => {
	}).finally(() => {
		state.userListLoading = false
	})
}
const transferProcess = (row: any) => {
	state.userPageParam.param.tenantId = row.tenantId
	state.transferProcessTaskId = row.taskId
	state.userCheckView = true
	loadUserList()
}
//重置
const reSetUserForm = (formEl: FormInstance | undefined) => {
	if (!formEl) return
	formEl.resetFields()
	state.userPageParam.page = 1
	loadUserList()
}
// 分页改变
const onUserHandleSizeChange = (val: number) => {
	state.userPageParam.pageSize = val;
	loadUserList()
}
// 分页改变
const onUserHandleCurrentChange = (val: number) => {
	state.userPageParam.page = val;
	loadUserList()
}
const doTransferProcess = (row: any) =>{
	ElMessageBox.confirm('流程将被转至' + row.staffName + '待办。注意：转办只适用于非会签任务。', '提示', {
			confirmButtonText: '确定',
		cancelButtonText: '取消',
	}).then(() => {
		//提交数据
		const loading = ElLoading.service({
			lock: true,
			text: '处理中',
			background: 'rgba(0, 0, 0, 0.7)',
		})
		workflowApi.transferProcess(state.transferProcessTaskId, row.id).then((data) => {
			if(data.code === 0){
				ElMessage.success('流程转办成功')
			}else{
				ElMessage.error(data.message)
			}
			loadList()
		}).catch(() => {
			ElMessage.error('流程转办失败')
		}).finally(() => {
			loading.close()
		})
	})
	state.userCheckView = false
}
</script>
